package lego.jbv;

import lejos.nxt.Button;
import lejos.nxt.LCD;
import lejos.nxt.LightSensor;
import lejos.nxt.SensorPort;
import lejos.robotics.subsumption.Behavior;
import lejos.util.Delay;

public class StayAlive implements Behavior {
	private boolean _suppressed = false;
	private LightSensor lightSensor;
	private final int fleeSpeed = 90;
	private Car car;

	public StayAlive(SensorPort port, Car _car) {
		car = _car;
		lightSensor = new LightSensor(port);
		lightSensor.setFloodlight(true);

		LCD.clear();
		LCD.drawString("Calibrate black", 0, 0);
		LCD.drawString("Press enter", 0, 1);

		Button.ENTER.waitForPressAndRelease();
		lightSensor.calibrateLow();

		LCD.drawString("Calibrate white", 0, 0);
		LCD.drawString("Press enter", 0, 1);

		Button.ENTER.waitForPressAndRelease();
		lightSensor.calibrateHigh();
	}

	@Override
	public boolean takeControl() {
		return lightSensor.getLightValue() > 70;
	}

	@Override
	public void action() {
		// TODO: Flee from white. Might be too simple.
		_suppressed = false;

		do {
			car.drive(-fleeSpeed, false);
			Delay.msDelay(300);
			car.rotate(-90, -fleeSpeed);
			car.rotate(-90, fleeSpeed);
			LCD.drawInt(lightSensor.getLightValue(), 4, 0, 5);
		} while (lightSensor.getLightValue() > 70
				&& !_suppressed);
	}

	@Override
	public void suppress() {
		_suppressed = true;
	}

}
